package com.xunmall.message.component.operation.service.impl;

import com.xunmall.base.dto.Result;
import com.xunmall.base.util.DateUtils;
import com.xunmall.message.constan.enums.SendStatus;
import com.xunmall.message.component.operation.model.OperationRecord;
import com.xunmall.message.component.operation.service.OperationRecordService;
import com.xunmall.message.constan.dto.GlobalErrorCode;
import com.xunmall.message.dto.MessagesForm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

@Slf4j
@Service
public class OperationRecordServiceImpl implements OperationRecordService {

    private
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public Result<String> addMsgOperation(MessagesForm entity , SendStatus status, String result) {
        if (StringUtils.isEmpty(entity.getAddress())) {
            return Result.ofParamsError(GlobalErrorCode.CODE_40001.getDesc());
        }
        List<OperationRecord> records = new ArrayList<>();
        Stream.of(entity.getAddress()).forEach(item -> {
            OperationRecord record = new OperationRecord();
            record.setTemplateId(entity.getTemplateId());
            record.setContent(entity.getContent());
            record.setExpires(entity.getExpires());
            record.setAddress(item);
            record.setResult(result);
            record.setStatus(status);
            record.setCreateDate(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            record.setFinishDate(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            records.add(record);
        });
        log.debug("insert all operation record , size:" + records.size());
        String collectionName = mongoTemplate.getCollectionName(OperationRecord.class) + LocalDate.now().toString().replace("-", "");
        mongoTemplate.insert(records, collectionName);
        log.debug("write login record success.");
        return Result.ofParamsError(GlobalErrorCode.CODE_200.getDesc());
    }
}
